package com.gopay.scheduler.job;

import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.gopay.common.constants.gsrt.CustSignedConstants;
import com.gopay.common.constants.txncd.IntTxnCd;
import com.gopay.common.cps.dao.gsrt.GsrtCustSignedDao;
import com.gopay.common.cps.manager.gsrt.GsrtCustSignedQueryManager;
import com.gopay.common.domain.gsrt.GsrtCustSigned;
import com.gopay.remote.cps.notify.order.MerNotifyOrderRemoteService;
import com.gopay.scheduler.GopayBaseJob;


/**
 * 处理G商融通投标超时订单清理任务。
 * 
 * 在此任务中，主要进行以下工作：
 * 根据超时时间清理除G商融通投标订单中，订单状态为处理中并且订单的创建时间与当前时间的时间差大于等于timeSpan
 * ，订单交易状态设置为“失效” 
 * 
 * @author ZYT
 */
public class CheckTimeoutGsrtCustSignedJob extends GopayBaseJob {


	@Resource(name = "merOrderNotifyClient")
    private MerNotifyOrderRemoteService merOrderNotifyClient;
	
	@Resource(name = "gsrtCustSignedQueryManager")
	private GsrtCustSignedQueryManager gsrtCustSignedQueryManager;
	
	@Resource(name = "gsrtCustSignedDao")
	private GsrtCustSignedDao gsrtCustSignedDao;

	private Logger logger = LoggerFactory
			.getLogger(CheckTimeoutGsrtCustSignedJob.class);
	public void doJobInternal() {
		logger.info("G商融通更新签约订单定时任务开始执行");
		// 根据超时时间清理除超时订单
		// 超时时间（分钟）
		int timeSpan = 20;
		List<Object> otherMainOrederList = gsrtCustSignedQueryManager.findTimeoutListByTimeSpan(timeSpan);
		if (!(otherMainOrederList.isEmpty())) {

			logger.info("已找到" + otherMainOrederList.size()
					+ "个超时订单, 现在开始清理这些订单");
			for (Object obj : otherMainOrederList) {

				String id = String.valueOf(obj);
				if(StringUtils.isNotBlank(id)){
					GsrtCustSigned gsrtCustSigned = gsrtCustSignedDao.find(GsrtCustSigned.class, Long.valueOf(id));
					if (gsrtCustSigned != null) {
						gsrtCustSigned.setSignedState(CustSignedConstants.SIGNED_STATE_04);
						gsrtCustSigned.setCommentRk("用户操作超时，页面失效");
						gsrtCustSigned.setLastUpdTs(new Date());
						gsrtCustSigned.setTranFinishTime(new Date());
						gsrtCustSignedDao.update(gsrtCustSigned);
					
						
						try {
							merOrderNotifyClient.addGsrtMerNotify(gsrtCustSigned.getMerOrderId(), gsrtCustSigned.getTransDtlSq(), IntTxnCd._01900.value, false);
							logger.info("G商融通清理超时签约业务订单：" + id + "订单成功");
							logger.info("G商融通清理超时签约业务订单merOrderNotifyClient---------------------------"+merOrderNotifyClient);
						} catch (Exception e) {
							// TODO: handle exception
							logger.error("cron执行成功网关G商融通签约处理成功，异步通知商户。签约业务表[" + id + "]");
							e.printStackTrace();
						}
					
					}
				}
               
			}
			logger.info("task - timeout the order has been done to clean up regularly");
		} else {
			
			logger.info("没有需要清理的超时请求");
		}

	}

}
